const api = require("../../../../utils/apiUtils");
const app = getApp();

Page({
  data: {
    deviceSn:null,
    devInfo:{},
    modalName:null,
    toLease:false,
    agreement:{
        title:'租赁服务协议',
        checked:false
    },
    timeCount:0
  },
  _checkOpenSlotResult:function(messageId){
    const _self = this;
    api.post(api.url.bxscnOpenSlotResult,{
        deviceSn:_self.data.deviceSn,
        messageId:messageId
    },res=>{
        if(res.data.code == 200){
            if(res.data.body.resultCode == 0){
                _self.data.timeCount =  _self.data.timeCount + 1;
                if( _self.data.timeCount < 15){
                    setTimeout(function(){
                        _self._checkOpenSlotResult(messageId);
                    },1000);
                }else{
                    my.hideLoading();
                    my.showModal({
                      content: '开仓失败，请检查设备是否有空仓或稍后再试',
                      showCancel:false
                    })
                }
            }else if(res.data.body.resultCode == 110){
                my.hideLoading();
                my.showModal({
                    content: '开仓失败，错误码：110',
                    showCancel:false
                })
            }else{
                my.hideLoading();
                my.showModal({
                    content: res.data.body.slotNum + "号仓室已打开，请将电源放入并插好电源和连接线",
                    showCancel:false
                })
            }
        }else if(res.data.msg){
            my.hideLoading();
            my.showModal({
              content: res.data.msg,
              showCancel:false
            })
        }else {
            my.hideLoading();
            my.showToast({
              content: '操作失败',
              icon:'error'
            })
        }
    })
  },

  _agreementInfo:function(){
      my.showLoading({
        title: '加载中...',
      })
      const _self = this;
      api.post(api.url.agreementInfo,{
          appId:my.getAccountInfoSync().miniProgram.appId,
          code:'RentAgreement'
      },res=>{
          my.hideLoading();
          if(res.data.code == 200){
              var agreement = _self.data.agreement;
              agreement.title = res.data.body.title;
              agreement.content = res.data.body.content;
              _self.setData({
                  agreement:agreement,
                  modalName:'agreement'
              });
          }else if(res.data.msg){
              my.showModal({
                content: res.data.msg,
                showCancel:false
              })
          }else {
              my.showToast({
                content: '获取失败',
                icon:'error'
              })
          }
      })
  },

  //勾选授权
  btnChangeRadio(){
      const agreement = this.data.agreement;
      agreement.checked = !agreement.checked;
      this.setData({agreement});
  },

  btnPay:function(){
      const self = this;
      if(!this.data.agreement.checked){
          this.data.toLease = true;
          this.btnAgreementInfo();
          return
      }
      api.post(api.url.bxscnPay,{
          payType:2,
          appId:my.getAppIdSync().appId,
          deviceSn:this.data.deviceSn
      },(res)=>{
          if(res.data.code==200){
              const tradeNo = res.data.body.tradeNo;
              my.tradePay ({
                tradeNO: tradeNo,
                success: res => {
                  console.error('调用 my.tradePay 成功: ', JSON.stringify(res));
                  self.toUnderway(tradeNo);
                },
                fail: error => {
                  console.error('调用 my.tradePay 失败: ', JSON.stringify(error));
                  my.showToast({
                    content: '支付失败',
                    icon:'error',
                    mask:true
                  })
                },
              });
          }else if(res.data.msg){
              my.showModal({
                  content: res.data.msg,
                  showCancel:false,
                  complete: () => {
                      my.reLaunch({
                        url: '/pages/index/index',
                      })
                  }
              })
          }else {
              my.showToast({
                content: '支付失败',
                icon:'error',
                mask:true
              })
          }
      })
  },

  btnRevert:function(){
      const _self = this;
      my.showModal({
        title: '温馨提示',
        content: '请确定是本会员租借了电池或授权归还电池！',
        complete: (res) => {
          if (res.confirm) {
              my.showLoading({
                title: '处理中...',
              })
              api.post(api.url.bxscnOpenSlot,{
                  deviceSn:_self.data.deviceSn
              },res=>{
                  my.hideLoading();
                  if(res.data.code == 200){
                      _self.data.timeCount = 0;
                      _self._checkOpenSlotResult(res.data.body.messageId);
                  }else if(res.data.msg){
                      my.showModal({
                        content: res.data.msg,
                        showCancel:false
                      })
                  }else {
                      my.showToast({
                        content: '操作失败',
                      })
                  }
              })
          }
        }
      })
  },

  btnAgreementInfo:function(){
      if(this.data.agreement.content){
          this.setData({
              modalName:'agreement'
          })
      }else{
          this._agreementInfo();
      }
  },

  btnHideModal:function(){
      this.setData({
          modalName:null
      })
  },

  btnChoiceAgreement:function(){
      const agreement = this.data.agreement;
      agreement.checked = true;
      this.setData({
          agreement:agreement,
          modalName:null
      });
      if(this.data.toLease){
          this.btnPay();
      }
  },

  toUnderway(tradeNo){
      console.log(tradeNo);
      my.redirectTo({
        url: './result?tradeNo='+tradeNo
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      if(options.deviceSn){
          this.setData({
              deviceSn:options.deviceSn
          })
      }
      const _self = this;
      api.post(api.url.bxscnScan,{
          appId:my.getAccountInfoSync().miniProgram.appId,
          deviceSn:options.deviceSn
      },res=>{
          if(res.data.code == 200){
              let agreement = _self.data.agreement;
              if(res.data.body.signingAgreement){
                  agreement.checked = true;
              }
              this.setData({
                  devInfo:res.data.body,
                  agreement:agreement
              })
              if(res.data.body.state == 2){
                  my.showModal({
                      content: '设备离线',
                      showCancel:false,
                      success(){
                          my.reLaunch({
                              url: '/pages/index/index',
                          })
                      }
                  })
              }
          }else if(res.data.msg){
              my.showModal({
                content: res.data.msg,
                showCancel:false,
                success(){
                  my.reLaunch({
                      url: '/pages/index/index',
                  })
                }
              })
          }else {
              my.showToast({
                content: '获取信息失败',
              })
              setTimeout(() => {
                  my.reLaunch({
                      url: '/pages/index/index',
                  })
              }, 1000);
          }
      })
  },

});
